<template>
  <div class="profile-container">
    <el-card>
      <template #header>
        <div class="header-content">
          <span>个人信息</span>
          <el-button type="primary" @click="handleEdit" v-if="!isEditing">
            编辑
          </el-button>
        </div>
      </template>

      <el-form
          ref="profileFormRef"
          :model="profileForm"
          :rules="profileRules"
          label-width="100px"
          :disabled="!isEditing"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="profileForm.password" show-password/>
        </el-form-item>
        <el-form-item v-if="isEditing">
          <el-button type="primary" @click="handleSave" :loading="loading">
            保存
          </el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="record-card">
      <template #header>
        <div class="header-content">
          <span>我的记录</span>
          <el-radio-group v-model="activeTab" size="small">
            <el-radio-button label="donation" @click="loadDonationRecords">我的捐赠</el-radio-button>
            <el-radio-button label="request" @click="loadRequestRecords">我的申请</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <div v-if="activeTab === 'donation'" class="record-list">
        <el-table :data="donationRecords" style="width: 100%">
          <el-table-column prop="material.name" label="物资名称"/>
          <el-table-column prop="donationRecord.donationNumber" label="捐赠数量"/>
          <el-table-column prop="donationRecord.donationTime" label="捐赠时间">
            <template #default="{ row }">
              {{ formatDate(row.donationRecord.donationTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="donationRecord.status" label="状态">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.donationRecord.status)">
                {{ getStatusText(row.donationRecord.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              v-model:current-page="donationCurrentPage"
              v-model:page-size="donationPageSize"
              :page-sizes="[10, 20, 30, 40]"
              :total="donationTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="donationSizeChange"
              @current-change="donationCurrentChange"
          />
        </div>
      </div>

      <div v-else class="record-list">
        <el-table :data="requestRecords" style="width: 100%">
          <el-table-column prop="materialVo.name" label="物资名称"/>
          <el-table-column prop="requestQuantity" label="申请数量"/>
          <el-table-column prop="requestTime" label="申请时间">
            <template #default="{ row }">
              {{ formatDate(row.requestTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button v-if="row.status === 0" type="danger" @click="deleteRequest(row)">取消申请</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              v-model:current-page="requestCurrentPage"
              v-model:page-size="requestPageSize"
              :page-sizes="[10, 20, 30, 40]"
              :total="requestTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="requestCurrentChange"
              @current-change="requestSizeChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {faker} from '@faker-js/faker'
import {getUserInfo, setUserInfo} from "@/utils/auth.js";
import {updateUserInfo} from "@/api/user.js";
import {cancelMaterialRequest, getMaterialDonations, getMaterialRequests} from "@/api/material.js";

// 个人信息表单
const profileFormRef = ref(null)
const isEditing = ref(false)
const loading = ref(false)
const profileForm = ref({
  username: '',
  email: '',
  phone: '',
  password: '',
})

const profileRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
  ]
}

// 记录相关
const activeTab = ref('donation')
const donationCurrentPage = ref(1)
const donationPageSize = ref(10)
const donationTotal = ref(100)
const requestCurrentPage = ref(1)
const requestPageSize = ref(10)
const requestTotal = ref(100)
const donationRecords = ref([])
const requestRecords = ref([])

// 获取角色类型
const getRoleType = (role) => {
  const types = {
    0: 'success',
    1: 'warning',
    2: 'danger'
  }
  return types[role] || 'info'
}

// 获取角色文本
const getRoleText = (role) => {
  const texts = {
    0: '捐赠者',
    1: '受捐者',
    2: '管理员'
  }
  return texts[role] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已批准',
    2: '已拒绝'
  }
  return texts[status] || '未知'
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

// 编辑相关方法
const handleEdit = () => {
  isEditing.value = true
}

const handleSave = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // TODO: 调用更新API
        await updateUserInfo(profileForm.value)
        setUserInfo(profileForm.value)
        ElMessage.success('保存成功')
        isEditing.value = false
        loadProfile()
      } catch (error) {
        console.error('保存失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

const cancelEdit = () => {
  isEditing.value = false
  loadProfile()
}

const deleteRequest = async (row) => {
  // TODO: 调用删除API
  try {
    console.log(row)
    await cancelMaterialRequest(row.requestId)
    ElMessage.success('取消申请成功')
    await loadRequestRecords()
  } catch (error) {
    console.error('取消申请失败:', error)
  }
}

// 加载个人信息
const loadProfile = () => {
  profileForm.value = getUserInfo();
}

// 加载记录
const loadDonationRecords = async () => {
  // TODO: 调用获取记录API
  const data = await getMaterialDonations({
    page: donationCurrentPage.value,
    size: donationPageSize.value,
    userId: getUserInfo().userId,
  })
  donationRecords.value = data.data.records
  donationTotal.value = data.data.total


}

const loadRequestRecords = async () => {
  const data = await getMaterialRequests({
    page: requestCurrentPage.value,
    size: requestPageSize.value,
    userId: getUserInfo().userId
  })
  requestRecords.value = data.data.records
  requestTotal.value = data.data.total
}

// 分页相关方法
const donationSizeChange = (val) => {
  donationPageSize.value = val
  loadDonationRecords()
}

const donationCurrentChange = (val) => {
  donationCurrentPage.value = val
  loadDonationRecords()
}

// 分页相关方法
const requestSizeChange = (val) => {
  requestPageSize.value = val
  loadRequestRecords()
}

const requestCurrentChange = (val) => {
  requestCurrentPage.value = val
  loadRequestRecords()
}

onMounted(() => {
  loadProfile()
  loadDonationRecords()
  loadRequestRecords()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-card {
  margin-top: 20px;
}

.record-list {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
